package com.example.seakdreamandroid.chatbot;


import static com.example.seakdreamandroid.Constant.BASE_URL;

import static com.mob.MobSDK.getContext;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.View;

import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.User;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class ChatbotActivity extends AppCompatActivity implements
        View.OnClickListener {

    //private HttpData httpData;// �첽�������
    private List<ListData> lists;
    private ListView lv;
    private EditText et_sendText;
    private Button btn_send;
    private String content_str; // �惦��EditText�@ȡ���Ĕ���
    private TextAdapter adapter;
    private double currentTime,oldTime = 0;//�Ի�ʱ��
    User user;
    private Bitmap bitmap;
    List<Map<String, String>> dataList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chatbot_main);
        Log.i("haha7", "----------7");
        initView();
        Log.i("haha8", "----------8");
    }

    /**
     * ʵ��������
     */
    private void initView(){
        lists = new ArrayList<ListData>();
        lv = (ListView) findViewById(R.id.lv);
        et_sendText = (EditText) findViewById(R.id.et_sendText);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);
        adapter = new TextAdapter(lists, this);
        lv.setAdapter(adapter);//��adapter
        ListData listData;
        listData = new ListData("睡不着吗，来聊聊吧~",ListData.RECEIVE, getTime());
        lists.add(listData);//��ӻ�ӭ��
        user = (User)getContext().getApplicationContext();
        setHead();

        ImageView back = findViewById(R.id.test_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        dataList.add(new HashMap<String, String>(){{
            put("role", "user");
            put("content", "请你扮演一个助眠师，与我进行交流");
        }});
        dataList.add(new HashMap<String, String>(){{
            put("role", "user");
            put("content", "接下来的所有对话你必须全部使用中文");
        }});
    }

    /**
     * ���û�ӭ��
     */
    /*public String getRandomWelcomeTips(){
//        String welcome_tip = null;
//        welcome_arry = this.getResources().getStringArray(getResources().getString(R.string.welcome_tips));//��string.xml�л�ȡ��Ϊwelcome_tips���ַ�������
//        int index = (int)(Math.random()*(welcome_arry.length - 1));//��ȡһ�������
//        welcome_tip = welcome_arry[index];
        return getResources().getString(R.string.welcome_tips);
    }*/

    /**
     * ����ʱ��
     * @return
     */
    private String getTime(){
        currentTime = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        Date curDate = new Date();
        String str = format.format(curDate);
        if(currentTime - oldTime >= 5*60*1000){//�������5���ӣ���ʾʱ��
            oldTime = currentTime;
            return str;
        }else{
            return "";
        }
    }



   /* public void getDataUrl(String data) {
        Log.i("haha---data=","------" + data);
        parseText(data);
    }

    public void parseText(String str){//����json
        try {
            JSONObject jb = new JSONObject(str);
            ListData listData;
            listData = new ListData(jb.getString("text"),ListData.RECEIVE, getTime());
            lists.add(listData);
            adapter.notifyDataSetChanged();//�����m�䣿��
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }*/

    @Override
    public void onClick(View v) {
        getTime();//����ʱ��
        content_str = et_sendText.getText().toString();//�@ȡEditText����
        et_sendText.setText("");
        String dropk = content_str.replace(" ", "");//ȥ���ո�
        String droph = dropk.replace("\n", "");//ȥ���س�
        ListData listData;
        listData = new ListData(content_str, ListData.SEND, getTime());
        listData.setHeadshot(bitmap);
        lists.add(listData);
        adapter.notifyDataSetChanged();
        setAnswer(droph);
        /*httpData = (HttpData) new HttpData(
                "http://www.tuling123.com/openapi/api?key=02dfb86de93f8a3e81dabd214a50c8fa&info=" + droph + "&userid=15602229049",
                this).execute();// �����Ѿ�ȥ���ո�ͻس�content_str������droph   ; execute()�����첽ͨ��

        Log.i("haha5", "----------"+httpData);*/

        if(lists.size() > 30){//�����Ļ�ϵĶԻ����ݶ���30�����Ƴ�ǰ�������
            for (int i = 0; i < lists.size(); i++) {
                lists.remove(i);
            }
        }
    }

    private void setAnswer(String question){

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("model", "gpt-3.5-turbo");
        dataList.add(new HashMap<String, String>(){{
            put("role", "user");
            put("content", question);
        }});
        paramMap.put("messages", dataList);
        JSONObject param = new JSONObject(paramMap);
        //2.创建请求对象（Request）,不需要设置请求体
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url("http://10.7.86.64:8090/"+"Chatbot/getAnswer"+"?question="+param.toString())
                //创建Request对象
                .build();
        //3.发送请求，获取响应

        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
                .connectTimeout(1000, TimeUnit.SECONDS)
                .writeTimeout(1000, TimeUnit.SECONDS)
                .readTimeout(1000, TimeUnit.SECONDS)
                .build();

        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("OkHttp","onFailure");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调
                String reslut = response.body().string();
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            ListData listData;
                            listData = new ListData(reslut,ListData.RECEIVE, getTime());
                            lists.add(listData);
                            adapter.notifyDataSetChanged();//�����m�䣿��
                        }catch (Exception e){
                            e.printStackTrace();
                        }//setview
                    }
                });
            }
        });
    }

    public void setHead(){
        String userId = user.getUserId();
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"UserInfo/getUserInfo"+"?id="+userId)
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("MineActivity","onFailure，请求数据失败");
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ChatbotActivity.this,"网络故障，请检查网络",Toast.LENGTH_LONG).show();

                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调
                Log.i("MineActivity","onResponse"+"成功");
                try {
                    String resultStr = response.body().string();
                    JSONObject object = new JSONObject(resultStr);
                    JSONObject data = object.getJSONObject("data");
                    if(!data.isNull("headshot")){
                        String headshot1 = data.getString("headshot");
                        byte[] bs = Base64.decode(headshot1, Base64.DEFAULT);
                        for (int i = 0; i < bs.length; ++i) {
                            if (bs[i] < 0) {
                                bs[i] += 256;
                            }
                        }
                        bitmap = BitmapFactory.decodeByteArray(bs,0,bs.length);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
                //setview
            }
        });

    }

    final X509TrustManager trustManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    };
    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }

    /**
     * description 忽略https证书验证
     *`在这里插入代码片`
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

